package services;

import dao.ReplyDAO;
import dao.UserDAO;
import model.Page;
import model.Reply;
import model.User;
import net.sf.json.JSONArray;
import utils.C3P0Util;
import utils.MyJSONUtils;

import java.sql.Connection;
import java.util.List;

/**
 * 提供回复的相关服务
 */
public class ReplyServices {

    private ReplyDAO replyDAO;
    private UserDAO userDAO;

    public ReplyServices() {
        this.replyDAO = new ReplyDAO();
        this.userDAO = new UserDAO();
    }

    /**
     * 获得某评论的一页回复，供[service]
     *
     * @param commentId 评论
     * @param page1     页
     * @param coon      连接
     * @return list
     */
    public List<Reply> getPageReplys(int commentId, Page page1, Connection coon) {
        //Connection coon = C3P0Util.getConnection();
        List<Reply> replyList = replyDAO.getReplyWithPage(commentId, page1.getStart(), page1.getPageSize(), coon);

        for (Reply reply : replyList) {
            User user = userDAO.getUserByName(reply.getUsername(), coon);
            reply.setUser(user);
        }

        return replyList;
    }

    /**
     * 获得某评论的一页回复,供[servlet]
     *
     * @param commentId 评论id
     * @param page      页数
     * @return list
     */
    public List<Reply> getPageReplys(String commentId, String page) {
        int cid = Integer.parseInt(commentId);

        Page page1 = new Page(Integer.parseInt(page));
        page1.setPageSize(5);

        return getPageReplys(cid, page1, null);
    }

    /**
     * 获取某评论下所有回复组成的分页，当前页为第一页
     *
     * @param commentId 评论id
     * @return 回复list
     */
    public Page getReplyPage(int commentId, Connection coon) {

        int count = replyDAO.getReplyCount(commentId, coon);

        Page page1 = new Page(1);
        page1.setPageSize(5);
        page1.setTotal(count);

        return page1;
    }

    /**
     * 获得某评论的第一页回复，刷新该评论的回复时用
     */
    public JSONArray getReplysWithPage(String commentId) {
        Connection coon = C3P0Util.getConnection();

        int cid = Integer.parseInt(commentId);

        Page page1 = getReplyPage(cid, coon);//获得页面
        List<Reply> list = getPageReplys(cid, page1, coon);//获得list

        JSONArray result = JSONArray.fromObject(page1, MyJSONUtils.jsonConfig);
        result.add(list, MyJSONUtils.jsonConfig);

        return result;
    }

    /**
     * 增加一条回复
     *
     * @param username  用户名
     * @param content   内容
     * @param commentId 评论id
     * @return true如果增加成功！
     */
    public boolean addReply(String username, String content, String commentId) {
        return replyDAO.addReply(username, content, Integer.parseInt(commentId));
    }
}
